#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging
import json
from aiohttp import web
from aiohttp.web import middleware
from aioweb import corelib


@middleware
async def template_middleware(request, handler):
    # print('template_middleware before')
    resp = await handler(request)
    # print('template_middleware after')
    try:
        params = await corelib.parse_param(request)
        if resp is None:
            resp = {}
        if isinstance(resp, dict):
            if hasattr(handler, '__template__'):
                resp = web.Response(body=request.app['__templating__'].get_template(
                    getattr(handler, '__template__')).render(**resp).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'
            elif hasattr(request, '__template__'):
                resp = web.Response(body=request.app['__templating__'].get_template(
                    getattr(request, '__template__')).render(**resp).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'
            else:
                resp = web.json_response(resp)
    except BaseException as e:
        logging.error('[ERROR]: %s' % corelib.printException(e))
        resp = web.json_response(
            {'code': -1, 'msg': 500, 'exception': corelib.printException(e)})
    return resp
